from flask import g
from flask import request
from flask.blueprints import Blueprint
from flask_restful.reqparse import RequestParser
from flask_restful import Resource

from models.news import UserChannel, Article
from toutiao import db
from toutiao.apps.home import comment
from toutiao.apps.home import detail
from toutiao.apps.home import history
from toutiao.utils.decorators import loginrequired
from toutiao.utils.parsers import check_channel_id
from toutiaoapi.flaskrestful import BaseApi

# 1.1 创建蓝图
home_blue = Blueprint('home', __name__, url_prefix='/app/v1_0')

# 1.2 创建api 实例,接管蓝图
home_api = BaseApi(home_blue)


# 2 定义类视图
# 首页信息获取
class Index(Resource):
    def get(self):
        # 1.验证参数
        parser = RequestParser()
        # 只验证频道id
        parser.add_argument('channel_id', type=check_channel_id, location='args', required=True)
        args = parser.parse_args()
        channel_id = args.get('channel_id')
        # channel_id 不会为0
        if int(channel_id) == 0:
            channel_id = 1
        # 2.查询获取数据
        articles = Article.query.filter_by(channel_id=channel_id, status=Article.STATUS.APPROVED).all()
        # 3.将对象列表数据转换为字典
        data_list = []
        for item in articles:
            data_list.append({
                "art_id": item.id,
                "title": item.title,
                "aut_id": item.user.id,
                "pubdate": item.ctime.strftime('%Y-%m-%d %H:%M:%S'),
                "aut_name": item.user.name,
                "comm_count": item.comment_count,
                "is_top": False,
                'cover': item.cover,
            })
        # 返回相应
        return {'pre_timestamp': 0, 'results': data_list}


# 获取所有频道的类
class AllChannel(Resource):
    def get(self):
        # 1.查询模型，获取对象列表     # 可见的 排序 序号升序,所有
        # channel = Channel.query.filter(Channel.is_visible == True).order_by(Channel.sequence.asc()).all()
        # 2.将对象列表转换为字典列表　　请查看上边的all_channel_fields
        # 3.返回相应       # 返回的数据  样式  再包装下
        # return marshal(channel, all_channel_fields, envelope='channel')
        from cache.channel import AllChannelCache
        return AllChannelCache.get()


# 用户频道
class UserChannelResource(Resource):
    # 调用登陆判断登陆的包
    method_decorators = {'put': [loginrequired]}

    def get(self):
        # 1.先获取用户的信息
        user_id = g.user_id
        # 2.如果是登陆用户，我们需要查询 登陆用户的关注频道
        if user_id:

            from cache.channel import UserChannelCache
            data = UserChannelCache(user_id).get()
        # 3如果是未登陆用户，我们需要查询 默认的频道
        else:

            from cache.channel import UserDefaultChannelsCache
            data = UserDefaultChannelsCache().get()

        # 4.必须有一个推荐
        # data_list=[{'id':0,'name':'推荐'}]
        # 5.返回相应
        return {'channels': data}

    # 修改关注频道必须是登陆用户
    def put(self):
        user_id = g.user_id
        # 1.接收数据
        channel_list = request.json.get('channels')
        # 2.更新数据(先全部变成没有)
        UserChannel.query.filter_by(user_id=user_id, is_deleted=False).update({'is_deleted': True})
        # 3.遍历前端传递的数据
        for channel in channel_list:
            # 对数据进行修改状态
            data = {'sequence': channel['seq'], 'is_deleted': False}
            # 做标记
            flag = UserChannel.query.filter_by(user_id=user_id, channel_id=channel['id']).update(data)
            # 判断标记是否存在,不存在就添加数据
            if flag == 0:
                userchannel = UserChannel()
                userchannel.user_id = user_id
                userchannel.sequence = channel.get('seq')
                userchannel.channel_id = channel.get('id')
                # 添加数据
                db.sessiion.add(userchannel)
            # 添加后保存数据
            db.session.commit()
            # 由于修改了数据,需要将缓存清除
            from cache.channel import UserChannelCache
            UserChannelCache(user_id).clear()
        # 4.返回数据
        return {'channels': channel_list}, 201


# 4. 让api实例 绑定类视图路由
home_api.add_resource(Index, '/articles')
# 获取所有频道
home_api.add_resource(AllChannel, '/channels')
# 获取用户关注的频道
home_api.add_resource(UserChannelResource, '/user/channels')

# --------详情页相关--------
# 获取详情页
home_api.add_resource(detail.DetailResource, '/articles/<article_id>')
# 关注用户
home_api.add_resource(detail.UserFllowing, '/user/followings')
# 取消关注
home_api.add_resource(detail.UserFollowingDelete, '/user/followings/<target>')
# 点赞
home_api.add_resource(detail.ArticleLiking, '/article/likings')
# 取消点赞
home_api.add_resource(detail.ArticleLikingDelete, '/article/likings/<target>')
# 不喜欢
home_api.add_resource(detail.ArticleDislike, '/article/dislikes')
# 取消不喜欢
home_api.add_resource(detail.ArticleDisLikeDelete, '/article/dislikes/<target>')
# 收藏文章
home_api.add_resource(detail.CollectionResource, '/article/collections')
# 取消收藏
home_api.add_resource(detail.CollectDelete, '/article/collections/<target>')

# ------评论相关-------
# 发表评论
home_api.add_resource(comment.Comments, '/comments')

# 对评论点赞
home_api.add_resource(comment.CommentLikingResource, '/comment/likings')
# 取消评论点赞
home_api.add_resource(comment.CommentLikingDelete, '/comment/likings/<target>')

# －－－－－历史记录－－－－－－
# 用户浏览记录
home_api.add_resource(history.UserHistory, '/user/histories')
